<template>
  <div class="home-page">
    <!-- <epPortalRender :routerPath="`/${currentTheme}`" /> -->
    <!-- 办事大厅首页 -->
    <home-render />

    <auth-modal ref="auth" />

    <ep-modal v-model="showCaptchaForm" :closeable=false width="400px">
      <captchaFormBad ref="captchaFormBad" @verifySuccess="showInvitationPdf" @closeModal="showCaptchaForm = false" />
    </ep-modal>

    <div class="pdfModal">
      <ep-modal v-model="showInvitationBadPdfModal" :closeable=false width="920px" top="0px">
        <invitationBad ref="invitationBad" :invitationData="invitationData"
          @closeModal="showInvitationBadPdfModal = false" />
      </ep-modal>
    </div>

  </div>
</template>

<script>
import authModal from "./components/authModal";
import captchaFormBad from "./captchaFormBad";
import invitationBad from 'ehub-common/components/business/invitation/badPdf/invitationBad'
import { invitationRlsQuery } from "./api.js";
import { getPassportList } from '@/api/passportRls'
import { rlsQuery } from '@/api/invitation'
import qrCodeContent from './components/qrCodeContent'
import mainDictionary from "ehub-common/utils/Dictionary";
import homeRender from './homeRender'
export default {
  components: { authModal, captchaFormBad, invitationBad, qrCodeContent, homeRender },
  computed: {
    currentTheme() {
      return window.localStorage.getItem("theme") || "themeThree";
    },
    token() {
      return this.$store.getters.getToken;
    },
    userMainInfo() {
      return this.$store.state.app.userMainInfo
    }
  },
  data() {
    return {
      invitationData: {},
      showCaptchaForm: false,
      showInvitationBadPdfModal: false,
      qrCodeShow: false,
      showIframe: false,
      qrCodeModelTitle: '',
      qrMode: '',
      qrCodeDetailObj: {}
    };
  },
  mounted() {
    this.$app.$on("handleActivityApply", this.handleActivityApply);
    this.$app.$on("handlePortalNavClick", this.handlePortalNavClick);
    this.$app.$on("handleMobileActivityApply", this.handleMobileActivityApply);
    this.$app.$on("handleMobileClickMenuItem", this.handleMobileClickMenuItem);
    // 打开智能客服
    this.$app.$on('handleOpenKefu', this.handleOpenKefu)
    // banner图下面的那4个点击事件
    this.$app.$on('panelOneClick', this.panelOneClick)
    // 新闻轮播图点击
    this.$app.$on('carouselItemClick', this.carouselItemClick)
    // 新闻列表点击
    this.$app.$on('newsItemClick', this.newsItemClick)
    // 投资指南点击
    this.$app.$on('investItemClick', this.investItemClick)
    // 服务导航点击
    this.$app.$on('serviceItemClick', this.serviceItemClick)
  },
  destroyed() {
    this.$app.$off("portalPersonalHandle");
    this.$app.$off("portalCorpHandle");
    this.$app.$off("handleActivityApply");
    this.$app.$off("handlePortalNavClick");
    this.$app.$off("handleMobileActivityApply");
    this.$app.$off("handleMobileClickMenuItem");
    this.$app.$off('handleOpenKefu', this.handleOpenKefu)
    this.$app.$off('panelOneClick', this.panelOneClick)
    this.$app.$off('carouselItemClick', this.carouselItemClick)
    this.$app.$off('newsItemClick', this.newsItemClick)
    this.$app.$off('investItemClick', this.investItemClick)
    this.$app.$off('serviceItemClick', this.serviceItemClick)
  },
  methods: {
    panelOneClick(data) {
      const map = [
        {
          path: '/regionalDynamicsDetail',
          query: {
            id: 1944,
          }
        },
        {
          path: '/regionalDynamicsDetail',
          query: {
            id: 1946,
          }
        },
        {
          path: '/regionalDynamicsDetail',
          query: {
            id: 1948,
          }
        },
        {
          path: '/regionalDynamicsDetail',
          query: {
            id: 1950,
          }
        }
      ]
      let index = data?.index
      let pathInfo = this.$router.resolve({
        path: map[index].path,
        query: {
          ...map[index].query
        }
      })
      window.open(pathInfo.href, '_blank')
    },
    carouselItemClick(item) {
      let pathInfo = this.$router.resolve({
        path: '/regionalDynamicsDetail',
        query: {
          id: item.id,
        }
      })
      window.open(pathInfo.href, '_blank')
    },
    newsItemClick(item) {
      let pathInfo = this.$router.resolve({
        path: '/regionalDynamicsDetail',
        query: {
          id: item.id,
        }
      })
      window.open(pathInfo.href, '_blank')
    },
    investItemClick(text) {
      const map = {
        "商务交流": 1954,
        "国际会展": 1956,
        "国际培训": 1958
      }
      let pathInfo = this.$router.resolve({
        path: '/regionalDynamicsDetail',
        query: {
          id: map[text],
        }
      })
      window.open(pathInfo.href, '_blank')
    },
    serviceItemClick(text) {
      const map = {
        "企业服务": 1960,
        "专业服务": 1962,
        "政策汇编": 1964,
        "交通、住宿、医疗": 1966
      }
      let pathInfo = this.$router.resolve({
        path: '/regionalDynamicsDetail',
        query: {
          id: map[text],
        }
      })
      window.open(pathInfo.href, '_blank')
    },
    handleOpenKefu() {
      window.open(global.CHAT_URL, "newwindow", "top=100,left=200,height=800, width=1500")
    },
    filterByValue(key, value) {
      const parent = mainDictionary.passReasonType.find((o) => o.value === key);
      if (parent) {
        const child = parent.children.find((child) => child.value === value);
        if (child) {
          return parent.label + " | " + child.label;
        }
      }
      return "---";
    },
    handleMobileClickMenuItem(menu) {
      console.log(menu, 'menu');
      if (!this.token) {
        this.$warn("请先登录");
        return;
      }
      let { code } = menu
      if (code === "access") {
        let params = {
          limit: 10,
          offset: 1,
          pageType: 'pass'
        }
        getPassportList(params).then(res => {
          if (res.code === 200 && res.data.length > 0) {
            console.log(res);
            this.qrCodeShow = true
            this.qrCodeModelTitle = '通行许可证'
            this.qrCodeDetailObj = res.data[0]

            this.qrMode = 'access'
          }
        })
      } else if (code === "invitation") {
        let params = {
          limit: 10,
          offset: 1,
          status: 'ISSUED',
          tabType: 'issued'
        }
        rlsQuery(params).then(res => {
          if (res.code === 200 && res.data.length > 0) {
            console.log(res);
            this.qrCodeShow = true
            this.qrCodeModelTitle = '邀请函'
            this.qrCodeDetailObj = res.data[0]

            this.qrMode = 'invitation'
          }
        })
      }
    },
    handleMobileActivityApply(data = {}) {
      console.log(data, 'data');

    },
    handleActivityApply(data = {}) {
      console.log(this.userMainInfo)
      console.log(this.userMainInfo.roles.map(v => v.roleCode).join(','))
      //
      let roles = this.userMainInfo.roles.map(v => v.roleCode).join(',')
      const { personInfo, applyBusiness = null, rootNode } = data; // 提供默认值，防止解构报错
      console.log(rootNode.enName, personInfo, applyBusiness)

      // 游客无需Token也能下载备案单
      // 路由跳转处理，判断是否有 applyBusiness 参数
      const query = applyBusiness ? { applyBusiness } : {};
      // 邀请备案凭证下载无需登录
      if (personInfo === 'invitation' && !this.token) {
        if (query.applyBusiness === '0') {
          this.$pop({
            type: 'warning',
            message: '请输入邀请备案凭证编号进行查询!'
          });
          return;
        }
        if (!query.applyBusiness || query.applyBusiness === null) {
          this.$pop({
            type: 'warning',
            message: '请输入邀请备案凭证编号!'
          });
          return;
        }
        this.invitationRlsQuery(query.applyBusiness)
        return;
      }


      console.log(this.token);
      // 如果没有 token，提示用户登录
      if (!this.token) {
        this.$warn("请先登录");
        return;
      }


      if (roles.indexOf('QYD_NORMAL_USER') !== -1 && rootNode.enName === 'ENTERPRISE') {
        this.$warn('个人用户不能办理法人相关业务！');
        return
      }

      if ((roles.indexOf('QYD_ENTERPRISE_OPERATOR') !== -1 || roles.indexOf('QYD_ENTERPRISE_ADMIN') !== -1) && rootNode.enName === 'INDIVIDUAL') {
        this.$warn('法人用户不能办理个人相关业务！');
        return
      }





      // 个人办事
      if (personInfo === 'inout') {
        if (applyBusiness === '0') {
          this.$router.push({
            path: "/business/tmpEntry",
            query,
          });
        } else if (applyBusiness === '1') {
          this.$router.push({
            path: "/business/portVisa",
            query,
          });
        }
      } else if (personInfo === 'luggage') {
        if (applyBusiness === '0') {
          this.$router.push({
            path: "/business/domesticLuggage",
            query,
          });
        } else if (applyBusiness === '1') {
          this.$router.push({
            path: "/business/outLuggage",
            query,
          });
        } else if (applyBusiness === '2') {
          this.$router.push({
            path: "/business/inLuggage",
            query,
          });
        }
      } else if (personInfo === 'invitation') {
        let query2 = query.applyBusiness === '0' ? {} : query;
        this.$router.push({
          path: "/business/invitationDownload/international",
          query: query2,
        });
      } else if (personInfo === 'access') {
        this.$router.push({
          path: "/business/invitationDownload/domestic",
          query,
        });
      }

      // 法人办事
      if (personInfo === 'activeManage') {
        if (roles.indexOf('QYD_ENTERPRISE_ADMIN') === -1) {
          this.$refs.auth.init()
        } else if (applyBusiness === '9') {
          this.$router.push({
            path: "/business/activityManagement",
            query,
          });
        } else {
          this.$router.push({
            path: "/business/activityManagement/detail/new",
            query,
          });
        }
      } else if (personInfo === 'personInvited') {
        if (roles.indexOf('QYD_ENTERPRISE_ADMIN') === -1) {
          this.$refs.auth.init()
        } else {
          if (applyBusiness === '0') {
            this.$router.push({
              path: "/business/invitationApply",
              query,
            });
          }
          if (applyBusiness === '1') {
            this.$router.push({
              path: "/business/passportBatch",
              query,
            });
          }
        }
      } else if (personInfo === 'goodsRegister') {
        if (roles.indexOf('QYD_ENTERPRISE_ADMIN') === -1) {
          this.$refs.auth.init()
        } else if (applyBusiness === '0') {
          this.$router.push({
            path: "/business/exhibitionItemAudit",
            query,
          });
        } else if (applyBusiness === '1') {
          this.$router.push({
            path: "/business/activityCargoAudit",
            query,
          });
        }
      } else if (personInfo === 'vehicleRegister') {
        if (roles.indexOf('QYD_ENTERPRISE_ADMIN') === -1) {
          this.$refs.auth.init()
        } else {
          this.$router.push({
            path: "/business/vehicleApply",
            query,
          });
        }
      }

    },
    invitationRlsQuery(applyBusiness) {
      let params = {
        limit: 10,
        offset: 1,
        badNumber: applyBusiness,
      };

      invitationRlsQuery(params).then((res) => {
        // console.log(res.data[0])
        if (res.code == 200) {
          if (!res.data || res.data.length === 0 || res.data[0] === null) {
            this.$pop({
              type: 'warning',
              message: '该邀请备案凭证不存在或未签发!'
            });
            return;
          } else {
            this.invitationData = res.data[0];
            this.showCaptchaForm = true;
            setTimeout(() => {
              console.log(this.$refs.captchaFormBad)
              this.$refs.captchaFormBad.form.phoneNum = res.data[0].contactInfo;
              // this.$refs.captchaFormBad.show = true;
            }, 0);

          }
        }
      });
    },

    // showInvitationPdf
    showInvitationPdf() {
      this.showCaptchaForm = false;
      console.log('验证成功')
      this.showInvitationBadPdfModal = true;
    },

    handlePortalNavClick(data = {}) {
      const { nav } = data
      console.log(nav);
      if (nav) {
        let dom = document.querySelector(`[data-nav-anchor=${nav}]`)
        // console.log(dom,dom.getBoundingClientRect().top);
        if (dom) {
          window.scrollTo({
            top: dom.offsetTop,
            behavior: 'smooth'
          })
        }
      }
    }
  },

};
</script>

<style lang="less" scoped>
.home-page {
  overflow: hidden;

  .pdfModal {
    /deep/ .ep-modal {
      background: transparent !important;
      box-shadow: none !important;
      margin-bottom: 5%;
    }

    /deep/ .ep-modal-height {
      border-top: transparent !important;
      border-bottom: none !important;
      overflow-x: none !important;
      overflow-y: none !important;
    }
  }

}

@media screen and (max-width: 768px) {
  .qrCodeModal {

    &/deep/.ep-modal,
    .ep-model {
      background: transparent !important;
      box-shadow: none !important;

      .ep-modal-body,
      .ep-model-body {
        padding: 0 !important;
      }
    }
  }

  .qrCode-content {
    width: 100%;
    margin-bottom: 16px;

    &-item {
      display: flex;
      // justify-content: space-between;
      width: 100%;
      font-size: 12px;
      margin-bottom: 8px;

      &-title {
        white-space: nowrap;
        width: 33%;
        color: #666;
      }

      &-desc {}
    }

  }

  .qrFooter {
    width: 100%;
    margin-top: 20px;
  }
}
</style>
